package com.ronghui.cash.controller;

import com.github.bingoohuang.patchca.color.ColorFactory;
import com.github.bingoohuang.patchca.custom.ConfigurableCaptchaService;
import com.github.bingoohuang.patchca.filter.predefined.*;
import com.github.bingoohuang.patchca.utils.encoder.EncoderHelper;
import com.github.bingoohuang.patchca.word.RandomWordFactory;
import com.ronghui.cash.parambean.MobileBean;
import com.ronghui.cash.parambean.SendVcodeBean;
import com.ronghui.cash.util.CodecUtil;
import com.ronghui.cash.vo.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Controller
public class CodeController extends BaseController {

	@Value("${cashpath}")
	String cashpath;
	/*@Autowired
	private SmsContext smsContext;*/

	@RequestMapping("vcode")
	@ResponseBody
	public Response sendVcode(@Validated SendVcodeBean sendVcode) {
		String mobile = sendVcode.getMobile();
		String imageCode = sendVcode.getImageCode();
		String type = type2String(sendVcode.getType());
		String imagevcodekey = "imagevcode:" + sendVcode.getMobile();

		String imageCodeInRedis = (String)super.redisTemplate.opsForValue().get(imagevcodekey);
		super.logger.debug("======================imagevcodekey=====:" + imagevcodekey);
		if (imageCodeInRedis == null) {
			return failure("图形验证码已失效");
		}

		if (!imageCodeInRedis.equalsIgnoreCase(imageCode)) {
			return failure("图形验证码错误");
		}

		// 验证过先删除redis的图形验证码数据
		// JedisService.del(imagevcodekey);
		String vcodeKey = "user:" + type + ":vcode:" + mobile;

		String vcodeKeyInRedis = (String)redisTemplate.opsForValue().get(vcodeKey);
		String vcode = "";
		if (vcodeKeyInRedis == null) {
			vcode = CodecUtil.createRandom(6);
		} else {
			vcode = vcodeKeyInRedis;
		}



		//测试环境写死短信验证码
		if("dev".equals(cashpath)){
			vcode="000000";
		}else{
			//		String sendSmsCode = smsContext.sendSms(mobile, SmsContent.getVcodeContent(vcode, type));
			//		if (!sendSmsCode.equals("0")) {
			//			super.logger.error("短信发送失败，错误码为:" + sendSmsCode);
			//			return failure("验证码发送失败，请稍后再试");
			//		}
		}
		redisTemplate.opsForValue().set(vcodeKey, vcode,900, TimeUnit.SECONDS);// 15分钟内有效
		super.logger.info("验证码vcode:" + vcode);

		return success("验证码已发送");
	}

	private String type2String(int type) {
		String result = "";
		switch (type) {
			case 1 :
				result = "login";
				break;
			case 2 :
				result = "register";
				break;
			case 3 :
				result = "findPassword";
				break;
			case 4 :
				result = "findPayPassword";
				break;
				default:;
		}
		return result;
	}

	private static ConfigurableCaptchaService cs = new ConfigurableCaptchaService();
	private static Random random = new Random();
	static {
		// cs.setColorFactory(new SingleColorFactory(new Color(25, 60, 170)));
		cs.setColorFactory(new ColorFactory() {
			@Override
			public Color getColor(int x) {
				int[] c = new int[3];
				int i = random.nextInt(c.length);
				for (int fi = 0; fi < c.length; fi++) {
					if (fi == i) {
						c[fi] = random.nextInt(71);
					} else {
						c[fi] = random.nextInt(256);
					}
				}
				return new Color(c[0], c[1], c[2]);
			}
		});

		// 以下的意思是，从1-9中，随机选4个字符
		RandomWordFactory wf = new RandomWordFactory();
		// wf.setCharacters("23456789abcdefghigkmnpqrstuvwxyzABCDEFGHIGKLMNPQRSTUVWXYZ");
		wf.setCharacters("0123456789");
		wf.setMaxLength(4);
		wf.setMinLength(4);
		cs.setWordFactory(wf);
	}

	@RequestMapping("getimgcode")
	public void getimgcode(@Validated MobileBean mobileBean, HttpServletRequest request, HttpServletResponse response) throws IOException {

		switch (random.nextInt(5)) {
			case 0 :
				cs.setFilterFactory(new CurvesRippleFilterFactory(cs.getColorFactory()));
				break;
			case 1 :
				cs.setFilterFactory(new MarbleRippleFilterFactory());
				break;
			case 2 :
				cs.setFilterFactory(new DoubleRippleFilterFactory());
				break;
			case 3 :
				cs.setFilterFactory(new WobbleRippleFilterFactory());
				break;
			case 4 :
				cs.setFilterFactory(new DiffuseRippleFilterFactory());
				break;
		}
		setResponseHeaders(response);
		String token = EncoderHelper.getChallangeAndWriteImage(cs, "png", response.getOutputStream());
		redisTemplate.opsForValue().set("imagevcode:" + mobileBean.getMobile(),token, 300, TimeUnit.SECONDS);// 300秒内有效
	}

	protected void setResponseHeaders(HttpServletResponse response) {
		response.setContentType("image/png");
		response.setHeader("Cache-Control", "no-cache, no-store");
		response.setHeader("Pragma", "no-cache");
		long time = System.currentTimeMillis();
		response.setDateHeader("Last-Modified", time);
		response.setDateHeader("Date", time);
		response.setDateHeader("Expires", time);
	}

}
